package com.CST.util;

import com.CST.vo.cb.BdCostVO;
import lombok.Data;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 *
 */
@Data
public class TreeUtil {
	  private List<BdCostVO> sourceList;
	  private int minLength;

	  public TreeUtil(List<BdCostVO> sourceList) {
			minLength = sourceList.stream().sorted(Comparator.comparingInt(o -> o.getEdExtraFirstCode().length()))
					.findFirst().get().getEdExtraFirstCode().length();
			this.sourceList = sourceList;
	  }

	  //建立树形结构
	  public List<BdCostVO> buildTree() {

			List<BdCostVO> treeList = new ArrayList<>();
			for (BdCostVO bdEnumdetail : getRootNode()) {
				  bdEnumdetail = buildChilTree(bdEnumdetail);
				  treeList.add(bdEnumdetail);
			}
			return treeList;
	  }

	  //递归，建立子树形结构
	  private BdCostVO buildChilTree(BdCostVO pNode) {
			List<BdCostVO> chilMenus = new ArrayList<>();
			for (BdCostVO menuNode : sourceList) {
				  if (menuNode.getEdExtraFirstCode().startsWith(pNode.getEdExtraFirstCode())
						  && menuNode.getEdExtraFirstCode().length() == pNode.getEdExtraFirstCode().length() + 2) {
						chilMenus.add(buildChilTree(menuNode));
				  }
			}
			  pNode.setChildrenList(chilMenus);
			return pNode;
	  }

	  //获取根节点
	  private List<BdCostVO> getRootNode() {
			List<BdCostVO> rootNodeList = new ArrayList<>();
			for (BdCostVO bdEnumdetail : sourceList) {
				  if (bdEnumdetail.getEdExtraFirstCode().length() == minLength) {
						rootNodeList.add(bdEnumdetail);
				  }
			}
			return rootNodeList;
	  }
}
